import { parse } from 'querystring';
import moment from 'moment';
/* eslint no-useless-escape:0 import/prefer-default-export:0 */

const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
export const isUrl = (path) => reg.test(path);
export const isAntDesignPro = () => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }

  return window.location.hostname === 'preview.pro.ant.design';
}; // 给官方演示站点用，用于关闭真实开发环境不需要使用的特性

export const isAntDesignProOrDev = () => {
  const { NODE_ENV } = process.env;

  if (NODE_ENV === 'development') {
    return true;
  }

  return isAntDesignPro();
};
export const getPageQuery = () => parse(window.location.href.split('?')[1]);

/**
 * 动态拼接不同模块、维度变量
 * @param {String} type el: pre\new\stock
 * @param {Array} dimensions el: ['面积]
 */
export const joinDimensionField = (type, dimensions = []) => {
  const DIMENSION_ENUM = { '面积': '_square', '套数': '_number', '金额': '_amount', '均价': '_price' }
  const result = {}
  dimensions.forEach(item => {
    result[item] = [type + DIMENSION_ENUM[item], type + DIMENSION_ENUM[item] + '_yoy', type + DIMENSION_ENUM[item] + '_mom', type]
  })
  return result
}

/**
 * 动态拼接不同模块、维度变量(存量房)
 * @param {Array} dimensions el: ['面积]
 */
export const joinDimensionField_stock = (dimensions = []) => {
  const DIMENSION_ENUM = { '面积': 'square', '套数': 'number', '金额': 'amount', '均价': 'price' }
  const result = {}
  dimensions.forEach(item => {
    result[item] = [DIMENSION_ENUM[item], DIMENSION_ENUM[item] + '_yoy', DIMENSION_ENUM[item] + '_mom']
  })
  return result
}

/**
 * 判断对象数组指定field是否都为空
 * @param {String} field 字段名
 * @param {Array} dataRow 图表数据列表
 */
export const isValueEmpty = (field, dataRow) => {
  if (!dataRow) return true
  return dataRow.every(item => !item[field] || item[field] === '0')
}

/**
 * 转化不同维度数值及单位
 * @param {*} type 维度
 * @param {*} amount 数值
 */
export const formatterUnitOfData = (type = '面积', amount, hideToFixed = false) => {
  const k = 10000
  const UNITS_ENUM = {
    '面积': ['㎡', '万㎡', '亿㎡', '万亿㎡'],
    '金额': ['元', '万元', '亿元', '万亿元'],
    '均价': ['元', '万元', '亿元', '万亿元'],
    '套数': ['套', '万套']
  }
  const c = Math.floor(Math.log(amount) / Math.log(k))
  const unit = (isNaN(c) || c === Infinity) ? '' : UNITS_ENUM[type][c]
  const _data = (amount / Math.pow(k, c))
  const value = isDecimal(_data) ? _data.toFixed(2) : _data
  return { value: (isNaN(value) || value === Infinity) ? 0 : value, unit }
}

/**
 * 月度日期格式化  => 2020年3月  找到其saq并返回
 * @param {string} date 月度日期默认字符串
 * @param {array} dateRange 日期列表
 * @param {array} seqRange seq列表
 */
export const seqFormatterMonDate = (date, dateRange, seqRange) => {
  let newArr = ''
  const strArr1 = date.slice(0, 5)
  const strArr2 = date.slice(5)
  if (strArr2.charAt(0) == '0') {
    newArr = strArr2.replace('0', '')
  }
  else {
    newArr = strArr2
  }
  const strValue = strArr1 + newArr
  const _index = dateRange.indexOf(strValue)
  const seqValue = seqRange[_index]
  return seqValue
}

/**
 * 月度日期格式化  => 2020-03-01  用于配合渲染from
 * @param {string} date 月度日期默认字符串
 */
export const formatterMon = (string) => {
  const str = string
  const reg = /[\u4e00-\u9fa5]/g
  const newStr = str.replace(reg, '-') + '1'
  // console.log(newStr)
  return (newStr)
}

/**
 * 根据tabkey选择请求参数（'presale','sale','stock'）
 * @param {string} type namespace类型  ('commerBuild','stockMonitor'..)
 * @param {string} index tabkey
 */
export const mapQueyType = (type, index) => {
  let TYPE_S = []
  switch (type) {
    default: TYPE_S = ['preSale', 'sale', 'stock']; break
    case 'commerBuild': TYPE_S = ['preSale', 'sale', 'stock']; break
    case 'stockMonitor': TYPE_S = ['deal', 'stockPeople']; break
    case 'rentMonitor': TYPE_S = ['rent', 'rentPeople']; break
  }
  const value = TYPE_S[Number(index) - 1]
  return (value)
}


/**
 * 上一级行政区域adcode计算
 * @param {string} code 当前adcode
 * @param {string} level 当前level
 */

export const beforeAdcode = (code, level) => {
  let adcode = '533100'
  if (level == 'district') {
    adcode = code.slice(0, 4) + '00'
  }
  if (level == 'city') {
    adcode = code.slice(0, 2) + '0000'
  }
  return adcode
}

/**
 * 将数组按照指定字段分组
 * @param {*} arr 数值
 * @param {*} param 分组字段
 */
export const groupBy = (arr, param) => {
  let groups = {}
  arr.forEach(o => {
    let value = JSON.stringify(o[param])
    groups[value] = groups[value] || []
    groups[value].push(o)
  })
  let temp = Object.keys(groups).map(i => {
    return groups[i]
  })
  return temp
}

/**
 * 将数组按照指定字段分组
 * @param {string} space 当前spacename
 * @param {string} func 请求操作function
 */
export const selectModel = (space, func) => {
  let str = ''
  str = space + '/' + func
  return str
}



/**
 * 获取当前时间
 *
 */
export const getCurrentDate = () => {
  return moment().format('YYYY-MM-DD');
}

/**
 * 根据指定字段获取数组目标值对应item
 * @param {*} list 数组
 * @param {*} target 目标值
 * @param {*} field 指定字段
 * @param {*} result 返回结果item
 */
export const findTreeItem = (list, target, field, result = {}) => {
  if (!list.length || !target) return {}
  for (let index = 0; index < list.length; index++) {
    const item = list[index];
    let tempResult = result
    if (item[field] == target) {
      tempResult = item
      return tempResult
    }
    if (item.children.length) {
      const data = findTreeItem(item.children, target, field, tempResult)
      if (data) {
        return data
      }
    }
  }
}
/**
 * 判断数字是否是小数
 * @param {*} number
 */
export const isDecimal = number => {
  if (!number) return false
  const numberStr = number + ''
  return numberStr.indexOf('.') > -1
}

/**
 * region_code格式化处理
 * @param {string} code
 */
export const formatterRegionCode = (code = '') => {
  const codeArr = code.slice(0,6)
  return codeArr
}
